package com.common.web.swagger;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import com.common.web.util.WebConstant;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger2 配置.
 * @author ficus.
 */
@Configuration
@ComponentScan(
	basePackages = { 
		"com.common.web.config",
		"com.common.web.socket",
		"com.common.web.aop",
		"com.common.web.service",
		"com.common.web.controller",
		"com.common.web.util",
		"com.common.web.test"
	})
@MapperScan("com.common.web.dao")
@EnableSwagger2
public class Swagger2 {

	@Autowired
	RestTemplateBuilder restTemplateBuilider;
	
	@Value("${Swagger2.includeBasePackage:}")
	private String includeBasePackage;
	
	private static final String splitor = ";";
	
	@Bean
	public RestTemplate restTemplate() {
		return restTemplateBuilider.build();
	}
	
    @Bean
    Docket createRestApi() {
        //添加head参数start
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name(WebConstant.TOKEN_KEY).description("token").modelRef(new ModelRef("string"))
                .parameterType("header").required(false).build(); //header中的ticket参数非必填，传空也可以
        pars.add(ticketPar.build());
        //添加head参数end
    	
    	// 过滤显示的API
    	ApiSelectorBuilder build=new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select();
    	build.paths(PathSelectors.any());
    	if(StringUtils.isNoneBlank(includeBasePackage)) {
    		build.apis(basePackage(includeBasePackage.split(splitor)));
    	}
    	return build.build().globalOperationParameters(pars);
    }
    
    private Predicate<RequestHandler> basePackage(final String[] basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private Function<Class<?>, Boolean> handlerPackage(final String[] basePackage)     {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }
    
    @SuppressWarnings("deprecation")
	private Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用Swagger2构建RESTful APIs")
                .version("1.0")
                .build();
    }

}
